package com.bw.a2207a.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType

/**
 *
 * @ClassName: BaseActivity
 * @Description: 通过反射获取ViewModel
 * @Author: zhangyanchao
 * @CreateDate: 2024/10/16 4:05 PM
 * @Version: 1.0
 */
abstract class BaseFragment<DB : ViewDataBinding, VM : ViewModel>(val layoutId: Int) :
    Fragment() {

    //延时初始化 lateinit
    lateinit var binding: DB
    lateinit var viewModel: VM


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(inflater, layoutId, container, false)
        binding.lifecycleOwner = this


        //通过反射，获取当前传入泛型参数 的对象
        val parameterizedType = javaClass.genericSuperclass as ParameterizedType
        //获取第二个泛型参数 vm
        val clazz = parameterizedType.actualTypeArguments[1] as Class<VM>
        //ViewModelProvider,获取viewModel 对象
        viewModel = ViewModelProvider(this)[clazz]

        initView()
        initData()

        return binding.root
    }

//    override fun onActivityCreated(savedInstanceState: Bundle?) {
//        super.onActivityCreated(savedInstanceState)
//        initView()
//        initData()
//
//    }

    abstract fun initData()

    abstract fun initView()

    override fun onDestroy() {
        super.onDestroy()
        //防止内存泄漏
        binding.unbind()
    }

}